<?php
namespace Modules\Feedback\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;


use Validator;
use ThrowException;
use Auth;

class FeedbackController extends Controller
{
    public function store(Request $req)
    {
        $rule = [
            'skus' => ['required', 'array'],
            // 'address_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $isNeedAddress = 0;
        $orders = [];
        $address = null;

        // 检查所有sku是否可出售
        $skuables = array_map(function($item) use($user) {
            $sku = Sku::getEntity([
                'id' => $item['id']
            ]);

            $sku->isCanBuy($user, $item['total']);

            return [
                'skuable' => $sku,
                'total' => $item['total']
            ];
        }, $req->skus);

        // 准备收货地址(如果有)
        $address = $user->getAddressOrDefault($req->input('address_id'));

        // // 创建统一订单
        // $unionOrder = new UnionOrder();

        $options = [
            'client_name' => Auth::clientName(),
            'client_type' => Auth::clientType(),
            'os_type' => Auth::osType(),
        ];

        $unionOrder = UnionOrder::initWith($skuables, $user, $address, $options);

        $unionOrder->createAll();

        $res = [
            'union_order' => [
                'id' => $unionOrder->id,
                'uuid' => $unionOrder->uuid
            ]
        ];

        if ($req->input('payment') === 'miniapp') {
            $clientName = Auth::clientName();

            $res['payment']['config'] = Payment::wechatPay($clientName, 'miniapp')->config($user, $unionOrder);
        }

        return $res;
    }
}
